package com.ldwx.center.service.impl;

import com.ldwx.center.service.FileService;
import com.ldwx.center.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Slf4j
@Service
public class FileServiceImpl implements FileService{
    @Value("${manager.config.save-file-path}")
    private String savePath;
    @Value("${manager.config.access-file-url}")
    private String accessUrl;
    @Override
    public Map<String,String> uploadFile(MultipartFile file) {
        Map<String,String> map = new HashMap<>();
        try {
            File parentFile = new File(savePath);
            if(!parentFile.exists()){
                parentFile.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            String newFileName = UUID.randomUUID()+fileName;
            File localFile = new File(savePath, newFileName);
            file.transferTo(localFile);
            map.put(fileName,accessUrl+newFileName);
        }catch (Exception e){
            log.error("上传文件失败："+file.getOriginalFilename(),e);
        }

        return map;
    }

    @Override
    public void downLoadFile(String name, HttpServletResponse response) {
        if(!StringUtils.isEmpty(name)){
            File file =new File(savePath,name);
            if(file.exists()){
                //如果文件存在
                byte[] buff = new byte[1024];
                BufferedInputStream bis = null;
                OutputStream os = null;
                try {
                    String contentType = new MimetypesFileTypeMap().getContentType(file);
                    response.setContentType(contentType);
                    response.setCharacterEncoding("utf-8");
                    response.setContentLengthLong(file.length());
                    //response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(name,"UTF-8"));
                    os = response.getOutputStream();
                    bis = new BufferedInputStream(new FileInputStream(file));
                    int i = bis.read(buff);
                    while (i != -1) {
                        os.write(buff, 0, buff.length);
                        os.flush();
                        i = bis.read(buff);
                    }
                } catch (IOException e) {
                    log.error("下载文件失败："+name,e);
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(os != null){
                        try {
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }
}
